import request from "@/utils/request";
import type { AxiosPromise } from "axios";
import type { AuthUrlReq, LoginData, LoginResponse } from "./types";
import { useUserStore } from "@/stores/modules/user";
import { vueMetaEnv } from "@/settings";
import { type RouteLocationNormalizedLoadedGeneric } from "vue-router";
import { storageUtil } from "@/utils/storage";

class WechatApi {
  // 获取公众号认证Url请求.
  authUrl(query: AuthUrlReq): AxiosPromise<string> {
    query.componentAppid = vueMetaEnv.APP_WECHAT_COMPONENT_ID;
    return request({
      url: `/v1/front/rbac/gzh/auth_url/${useUserStore().user.tenant}/${vueMetaEnv.APP_WECHAT_APPID}`,
      method: "get",
      params: query,
      headers: {
        Authorization: false
      }
    });
  }
  // 从路由中获取登录数据
  createLoginData(
    route: RouteLocationNormalizedLoadedGeneric,
    redirectUri: string = ""
  ): LoginData {
    useUserStore().user.tenant = route.params.tenant as string;
    const data = {
      tenant: route.params.tenant,
      componentAppid: route.params.componentAppid,
      code: route.query.code,
      state: route.query.state,
      appId: route.query.appid
    } as LoginData;
    storageUtil.setCode(data.code);

    //回调地址.
    if (redirectUri) {
      data.redirectUri = window.location.href.slice(0, -route.fullPath.length) + redirectUri;
    }
    return data;
  }

  // 静默登录公众号.
  login(data: LoginData): AxiosPromise<LoginResponse> {
    return request({
      url: "/v1/front/rbac/gzh/auth",
      method: "post",
      data,
      headers: {
        Authorization: false
      }
    });
  }

  // 公众号用户注册登录.
  register(data: LoginData): AxiosPromise<LoginResponse> {
    return request({
      url: "/v1/front/rbac/gzh/register",
      method: "post",
      data,
      headers: {
        Authorization: false
      }
    });
  }
}

const wechatApi = new WechatApi();
export { wechatApi };
